package com.example.testplatform.controller;

import com.example.testplatform.common.LogUtils;
import com.example.testplatform.common.Result;
import com.example.testplatform.entity.Product;
import com.example.testplatform.service.ProductService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    
    private static final Logger logger = LogUtils.getLogger(ProductController.class);
    
    @Autowired
    private ProductService productService;
    
    // 获取产品列表
    @GetMapping
    public Result<Map<String, Object>> getProductList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String search) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_ATTEMPT", "product", "尝试获取产品列表");
        LogUtils.logApiRequest(logger, "GET", "/api/products", "page=" + page + ", pageSize=" + pageSize + ", search=" + search);
        LogUtils.debug(logger, () -> "开始处理获取产品列表请求，页码=" + page + "，每页条数=" + pageSize + "，搜索关键词=" + search);
        
        try {
            // 验证参数
            if (page == null || page <= 0) {
                LogUtils.warn(logger, "获取产品列表失败: 页码必须大于0，当前值=" + page);
                LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_FAILED", "product", "获取产品列表失败: 页码无效");
                return Result.fail("页码无效");
            }
            
            if (pageSize == null || pageSize <= 0 || pageSize > 100) {
                LogUtils.warn(logger, "获取产品列表失败: 每页条数必须在1-100之间，当前值=" + pageSize);
                LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_FAILED", "product", "获取产品列表失败: 每页条数无效");
                return Result.fail("每页条数无效");
            }
            
            LogUtils.info(logger, () -> "执行获取产品列表操作，页码=" + page + "，每页条数=" + pageSize + "，搜索关键词=" + search);
            Map<String, Object> data = productService.getProductList(page, pageSize, search);
            
            LogUtils.debug(logger, () -> "获取产品列表成功，总记录数=" + data.get("total") + "，当前页记录数=" + ((List<?>)data.get("products")).size());
            LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_SUCCESS", "product", "获取产品列表成功，页码=" + page + "，每页条数=" + pageSize);
            LogUtils.logPerformance(logger, "getProductList", startTime, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "获取产品列表请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
            return Result.success(data);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/products", e);
            LogUtils.error(logger, "获取产品列表过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_FAILED", "product", "获取产品列表失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getProductList", startTime, System.currentTimeMillis());
            return Result.fail("获取产品列表失败: " + e.getMessage());
        }
    }
    
    // 获取产品详情
    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_ATTEMPT", "product", "尝试获取产品详情");
        LogUtils.logApiRequest(logger, "GET", "/api/products/" + id, null);
        LogUtils.debug(logger, () -> "开始处理获取产品详情请求，产品ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "获取产品详情失败: 产品ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_FAILED", "product", "获取产品详情失败: 产品ID无效");
                return Result.fail("产品ID无效");
            }
            
            LogUtils.info(logger, () -> "执行获取产品详情操作，产品ID=" + id);
            Product product = productService.getProductById(id);
            
            if (product != null) {
                LogUtils.debug(logger, () -> "获取产品详情成功，产品ID=" + id + "，产品名称=" + product.getProductName());
                LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_SUCCESS", "product", "获取产品详情成功，产品ID=" + id);
                LogUtils.logPerformance(logger, "getProductById", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "获取产品详情请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success(product);
            } else {
                LogUtils.warn(logger, "获取产品详情失败: 产品不存在，产品ID=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_FAILED", "product", "获取产品详情失败: 产品不存在");
                return Result.fail("产品不存在");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/products/" + id, e);
            LogUtils.error(logger, "获取产品详情过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_FAILED", "product", "获取产品详情失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getProductById", startTime, System.currentTimeMillis());
            return Result.fail("获取产品详情失败: " + e.getMessage());
        }
    }
    
    // 创建产品
    @PostMapping
    public Result<String> createProduct(@RequestBody Product product) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_CREATE_ATTEMPT", "product", "尝试创建产品");
        LogUtils.logApiRequest(logger, "POST", "/api/products", product != null ? product.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理创建产品请求");
        
        try {
            // 验证参数
            if (product == null) {
                LogUtils.warn(logger, "创建产品失败: 产品信息不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAILED", "product", "创建产品失败: 产品信息不能为空");
                return Result.fail("产品信息不能为空");
            }
            
            if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
                LogUtils.warn(logger, "创建产品失败: 产品名称不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAILED", "product", "创建产品失败: 产品名称不能为空");
                return Result.fail("产品名称不能为空");
            }
            
            LogUtils.info(logger, () -> "执行创建产品操作，产品名称=" + product.getProductName());
            boolean success = productService.createProduct(product);
            
            if (success) {
                LogUtils.debug(logger, () -> "创建产品成功，产品名称=" + product.getProductName() + "，产品ID=" + product.getId());
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_SUCCESS", "product", "创建产品成功，产品名称=" + product.getProductName());
                LogUtils.logPerformance(logger, "createProduct", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "创建产品请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("创建产品成功");
            } else {
                LogUtils.warn(logger, () -> "创建产品失败: 未知原因，产品名称=" + product.getProductName());
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAILED", "product", "创建产品失败: 未知原因");
                return Result.fail("创建产品失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "POST", "/api/products", e);
            LogUtils.error(logger, "创建产品过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAILED", "product", "创建产品失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "createProduct", startTime, System.currentTimeMillis());
            return Result.fail("创建产品失败: " + e.getMessage());
        }
    }
    
    // 更新产品
    @PutMapping("/{id}")
    public Result<String> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_UPDATE_ATTEMPT", "product", "尝试更新产品");
        LogUtils.logApiRequest(logger, "PUT", "/api/products/" + id, product != null ? product.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理更新产品请求，产品ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "更新产品失败: 产品ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAILED", "product", "更新产品失败: 产品ID无效");
                return Result.fail("产品ID无效");
            }
            
            if (product == null) {
                LogUtils.warn(logger, "更新产品失败: 产品信息不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAILED", "product", "更新产品失败: 产品信息不能为空");
                return Result.fail("产品信息不能为空");
            }
            
            if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
                LogUtils.warn(logger, () -> "更新产品失败: 产品名称不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAILED", "product", "更新产品失败: 产品名称不能为空");
                return Result.fail("产品名称不能为空");
            }
            
            product.setId(id);
            LogUtils.info(logger, () -> "执行更新产品操作，产品ID=" + id + "，产品名称=" + product.getProductName());
            boolean success = productService.updateProduct(product);
            
            if (success) {
                LogUtils.debug(logger, () -> "更新产品成功，产品ID=" + id + "，产品名称=" + product.getProductName());
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_SUCCESS", "product", "更新产品成功，产品ID=" + id);
                LogUtils.logPerformance(logger, "updateProduct", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "更新产品请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("更新产品成功");
            } else {
                LogUtils.warn(logger, "更新产品失败: 产品不存在，产品ID=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAILED", "product", "更新产品失败: 产品不存在");
                return Result.fail("更新产品失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/products/" + id, e);
            LogUtils.error(logger, "更新产品过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAILED", "product", "更新产品失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "updateProduct", startTime, System.currentTimeMillis());
            return Result.fail("更新产品失败: " + e.getMessage());
        }
    }
    
    // 删除产品
    @DeleteMapping("/{id}")
    public Result<String> deleteProduct(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_DELETE_ATTEMPT", "product", "尝试删除产品");
        LogUtils.logApiRequest(logger, "DELETE", "/api/products/" + id, null);
        LogUtils.debug(logger, () -> "开始处理删除产品请求，产品ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "删除产品失败: 产品ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAILED", "product", "删除产品失败: 产品ID无效");
                return Result.fail("产品ID无效");
            }
            
            LogUtils.info(logger, () -> "执行删除产品操作，产品ID=" + id);
            boolean success = productService.deleteProduct(id);
            
            if (success) {
                LogUtils.debug(logger, () -> "删除产品成功，产品ID=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_SUCCESS", "product", "删除产品成功，产品ID=" + id);
                LogUtils.logPerformance(logger, "deleteProduct", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "删除产品请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("删除产品成功");
            } else {
                LogUtils.warn(logger, "删除产品失败: 产品不存在，产品ID=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAILED", "product", "删除产品失败: 产品不存在");
                return Result.fail("删除产品失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "DELETE", "/api/products/" + id, e);
            LogUtils.error(logger, "删除产品过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAILED", "product", "删除产品失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "deleteProduct", startTime, System.currentTimeMillis());
            return Result.fail("删除产品失败: " + e.getMessage());
        }
    }
    
    // 更新产品状态
    @PutMapping("/{id}/status")
    public Result<String> updateProductStatus(@PathVariable Long id, @RequestBody Map<String, Integer> params) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_ATTEMPT", "product", "尝试更新产品状态");
        LogUtils.logApiRequest(logger, "PUT", "/api/products/" + id + "/status", params != null ? params.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理更新产品状态请求，产品ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "更新产品状态失败: 产品ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAILED", "product", "更新产品状态失败: 产品ID无效");
                return Result.fail("产品ID无效");
            }
            
            if (params == null) {
                LogUtils.warn(logger, "更新产品状态失败: 参数不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAILED", "product", "更新产品状态失败: 参数不能为空");
                return Result.fail("参数不能为空");
            }
            
            Integer status = params.get("status");
            if (status == null) {
                LogUtils.warn(logger, "更新产品状态失败: 状态参数不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAILED", "product", "更新产品状态失败: 状态参数不能为空");
                return Result.fail("状态参数不能为空");
            }
            
            LogUtils.info(logger, () -> "执行更新产品状态操作，产品ID=" + id + "，新状态=" + status);
            boolean success = productService.updateProductStatus(id, status);
            
            if (success) {
                LogUtils.debug(logger, () -> "更新产品状态成功，产品ID=" + id + "，状态=" + status);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_SUCCESS", "product", "更新产品状态成功，产品ID=" + id + "，状态=" + status);
                LogUtils.logPerformance(logger, "updateProductStatus", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "更新产品状态请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("更新产品状态成功");
            } else {
                LogUtils.warn(logger, "更新产品状态失败: 产品不存在，产品ID=" + id);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAILED", "product", "更新产品状态失败: 产品不存在");
                return Result.fail("更新产品状态失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/products/" + id + "/status", e);
            LogUtils.error(logger, "更新产品状态过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAILED", "product", "更新产品状态失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "updateProductStatus", startTime, System.currentTimeMillis());
            return Result.fail("更新产品状态失败: " + e.getMessage());
        }
    }
    
    // 获取所有产品（不分页）
    @GetMapping("/all")
    public Result<List<Product>> getAllProducts() {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_ALL_QUERY_ATTEMPT", "product", "尝试获取所有产品（不分页）");
        LogUtils.logApiRequest(logger, "GET", "/api/products/all", null);
        LogUtils.debug(logger, () -> "开始处理获取所有产品请求");
        
        try {
            LogUtils.info(logger, () -> "执行获取所有产品操作");
            List<Product> products = productService.getAllProducts();
            
            LogUtils.debug(logger, () -> "获取所有产品成功，共获取到" + products.size() + "个产品");
            LogUtils.logBusiness(logger, "PRODUCT_ALL_QUERY_SUCCESS", "product", "获取所有产品成功，总数量=" + products.size());
            LogUtils.logPerformance(logger, "getAllProducts", startTime, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "获取所有产品请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
            return Result.success(products);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/products/all", e);
            LogUtils.error(logger, "获取所有产品过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_ALL_QUERY_FAILED", "product", "获取产品列表失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getAllProducts", startTime, System.currentTimeMillis());
            return Result.fail("获取产品列表失败: " + e.getMessage());
        }
    }
}